package com.bsoft.gol.hcs.service.rpc.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.bsoft.gol.hcs.common.bean.request.FamilyMemberRequest;
import hcn.util.BaseResponse;
import hcn.service.commonClinical.qo.SysParameterRequest;
import com.bsoft.gol.hcs.common.bean.response.AccountFamilyResponse;
import com.bsoft.gol.hcs.common.bean.response.BasAccountFamily;
import com.bsoft.gol.hcs.common.bean.response.ParameterResponse;
import com.bsoft.gol.hcs.common.bean.response.SysParameterResponse;
import com.bsoft.gol.hcs.enumcase.InterfaceTypeEnum;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.satisfaction.bean.request.GetQuestionnaireDetailRequest;
import com.bsoft.gol.hcs.satisfaction.bean.response.EditorQuestionnaireDetailRes;
import com.bsoft.gol.hcs.service.rpc.IBaseParameterService;
import org.atag.util.common.RpcUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.bsoft.gol.hcs.utils.*;
import org.atag.util.http.KdHttpClientUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 基础服务
 * @author: chenJij@bsoft.com.cn
 * @date: 2022/7/14 15:28
 */
@Service("baseParameterService")
public class BaseParameterServiceImpl implements IBaseParameterService {
    private final static Logger log = LoggerFactory.getLogger(BaseParameterServiceImpl.class);
    @Value("${project_source}")
    private String projectSource;

    @Override
    public BaseResponse<EditorQuestionnaireDetailRes> getQuestionnaireDetail(GetQuestionnaireDetailRequest request) {
        log.info( " 同步表单编辑器数据： "+JSONObject.toJSONString(request));
        BaseResponse<EditorQuestionnaireDetailRes> result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url1= Constants.EDITOR_FOLLOW_UP + Constants.GET_QUESTIONNAIRE_DETAIL;
        log.info("--------------url1"+url1);
        log.info("-------------参数"+jsonParams);
        String url= "http://10.10.10.54/followup" + Constants.GET_QUESTIONNAIRE_DETAIL;
        log.info("---------------url"+url);
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONObject("data").isEmpty()) {
                EditorQuestionnaireDetailRes res = JSONObject.parseObject(
                        jsonObject.getJSONObject("data").toJSONString(), EditorQuestionnaireDetailRes.class);
                result.setData(res);
                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取编辑器信息失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        log.info("getQuestionnaireDetail:{}", result);
        return result;
    }

    /**
     * 健康通，查询患者家庭成员
     */
    @SuppressWarnings("unchecked")
    private List<AccountFamilyResponse> hcnGetFamilyList(FamilyMemberRequest request){
        try {
            //rpc调用查询家庭成员列表
            log.info("rpc查询家庭成员列表, 参数:includeSelf-{}, userId-{}", request.getIncludeSelf(), request.getUserId());
            List<Map<String, Object>> result = RpcUtil.invoke("hcn.person", "getAccompanyList", request.getIncludeSelf(), request.getUserId());
            if(!CollectionUtils.isEmpty(result)){
                ObjectMapper mapper = new ObjectMapper();
                mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                return result.stream().map(m-> mapper.convertValue(m, AccountFamilyResponse.class)).collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error("rpc 健康通，查询患者家庭成员失败", e);
        }
        return Collections.emptyList();
    }

    @Override
    public BaseResponse<List<AccountFamilyResponse>> findFamilyMemberList(FamilyMemberRequest request) {
        BaseResponse<List<AccountFamilyResponse>> result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url = "";
        if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
            log.info("进入互联网医院，查询患者家庭成员");
            if (CommonUtils.isNotEmpty(request.getPatientCode())) {
                url = Constants.HOL_FAMILY_URL + Constants.LIST_FAMILY + "?userId=" + request.getUserId()
                        + "&patientCode=" + request.getPatientCode() + "&t=1";
            } else {
                url = Constants.HOL_FAMILY_URL + Constants.LIST_FAMILY + "?userId=" + request.getUserId() + "&t=1";
            }
        } else {
            log.info("进入健康通，查询患者家庭成员");
//            url = Constants.GOL_FAMILY_URL + Constants.LIST_FAMILY;
            //20210928 rpc改造
            List<AccountFamilyResponse> accountFamilyResponses = hcnGetFamilyList(request);
            if(CollectionUtils.isEmpty(accountFamilyResponses)){
                result.setCode(ResultCode.SUCCESS);
                result.setMessage("没有患者家庭成员");
                return result;
            }
            result.setCode(ResultCode.SUCCESS);
            result.setData(accountFamilyResponses);
            return result;
        }
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                List<AccountFamilyResponse> responseList = new ArrayList<>();
                List<BasAccountFamily> list = new ArrayList<>();
                if (InterfaceTypeEnum.GOL.getCode().equals(projectSource)) {
                    responseList = JSONObject.parseArray(
                            jsonObject.get("data").toString(), AccountFamilyResponse.class);
                } else {
                    list = JSONObject.parseArray(
                            jsonObject.get("data").toString(), BasAccountFamily.class);
                    for (BasAccountFamily family : list) {
                        AccountFamilyResponse response = new AccountFamilyResponse();
                        response.setUserId(family.getId().toString());
                        response.setUserName(family.getRealname());
                        response.setAge(String.valueOf(DateUtil.getAgeByBirth(family.getBirthdate())));
                        if (family.getBirthdate() != null) {
                            response.setBirthday(DateUtil.dateFormate(family.getBirthdate(), "yyyy-MM-dd"));
                        }
                        response.setCardType(family.getCardtype());
                        response.setCardNo(family.getIdcard());
                        response.setRelation(family.getRelation());
                        response.setPhotoFileId(family.getHeader());
                        response.setRegionCode(family.getAreaCode());
                        response.setRegionCodeText(family.getArea());
                        response.setMobile(family.getMobile());
                        response.setCertificationValidityPeriod(family.getCertificationValidityPeriod());
                        response.setCreateRecordDate(new Date());
                        response.setSexCode(family.getSexcode().toString());
                        response.setHisBusCardList(family.getHisBusCardList());
                        responseList.add(response);
                    }

                }
                result.setData(responseList);
                result.setCode(ResultCode.SUCCESS);
            } else if (jsonObject.getInteger("code") == ResultCode.SUCCESS &&
                    jsonObject.get("data") == null) {
                result.setCode(ResultCode.SUCCESS);
                result.setMessage("没有患者家庭成员");
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取患者家庭成员失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        log.info("findFamilyMemberList:{}", result);
        return result;

    }

    @Override
    public BaseResponse<List<ParameterResponse>> getSysParameterList(SysParameterRequest request) {
        BaseResponse<List<ParameterResponse>> result = new BaseResponse();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url = "";
        JSONObject jsonObject = new JSONObject();
        if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
            log.info("进入互联网医院，查询系统参数");
            url= Constants.HOL_FAMILY_URL + Constants.GET_SYS_PARAMETER_LIST;
            jsonParams.remove("type");
            jsonParams.remove("organizationType");
            jsonParams.put("hospitalCode", jsonParams.remove("organizationId"));
             jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
            try {
                if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                        jsonObject.get("data") != null) {
                    List<SysParameterResponse> list = JSONObject.parseArray(
                            jsonObject.get("data").toString(), SysParameterResponse.class);
                    List<ParameterResponse> responseList = new ArrayList<>();
                    for (SysParameterResponse sys : list) {
                        ParameterResponse response = new ParameterResponse();
                        BeanUtils.copyProperties(sys,response);
                        response.setOrganizationId(sys.getHospitalCode());
                        response.setOrganizationName(sys.getHospitalName());
                        responseList.add(response);
                    }
                    result.setData(responseList);
                    result.setCode(ResultCode.SUCCESS);
                } else {
                    result.setCode(ResultCode.ERROR);
                    result.setMessage("查询系统参数失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                result.setCode(Constants.ERR_CODE);
            }
        }else{
            log.info("进入健康通，查询系统参数");
            url= Constants.GOL_FAMILY_URL + Constants.GOL_SYS_PARAMETER_LIST;
             jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
             try {
                if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                        jsonObject.get("data") != null){
                    JSONArray data =(JSONArray)jsonObject.get("data");
                    List<ParameterResponse> responseList = new ArrayList<>();
                    for(int i = 0; i < data.size(); i++) {
                        JSONObject object = data.getJSONObject(i);
                        ParameterResponse response = JSONObject.parseObject(object.toJSONString(), ParameterResponse.class);
                        response.setParameterKey(object.get("parameterKey ").toString());
                        responseList.add(response);
                    }

//                    List<ParameterResponse> responseList = JSONObject.parseArray(data.toJSONString(), ParameterResponse.class);
                    result.setData(responseList);
                    result.setCode(ResultCode.SUCCESS);
                }
             }catch (Exception e) {
                 e.printStackTrace();
                 result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                 result.setCode(Constants.ERR_CODE);
             }
             return result;
        }
        log.info("findFamilyMemberList:{}", result);
        return result;
    }

    public static void main(String[] args) {
        JSONObject jsonParams = JSONObject.parseObject("{\"deviceType\":\"1\",\"questionnaireId\":\"db4d3b46-03b5-4cb6-be7a-4b28efa5f2d3\",\"showType\":\"2\",\"userInfoId\":\"6670d755-35fa-4e30-88b9-b7a48245b05e\"}");
        String url="https://weixin.hz3yy.com/followup/api/auth/editorQuestionnaireTitle/getQuestionnaireDetail";
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        log.info(jsonObject+"--------");
    }
}
